/*
 * @Author: xiehangyun
 * @Date: 2025-02-20 11:55:31
 * @Last Modified by: xiehangyun
 * @Last Modified time: 2025-02-20 16:20:50
 */

import FabricCanvas from '@/myFabric/FabricCanvas';
import { fabric } from 'fabric';

// 绘制裁剪效果的矩形对象
export default class FabcriClippingRect extends fabric.Rect {
  constructor(options: any = {}) {
    super(options);
    this.setControlsVisibility({
      mt: true,
      mb: true,
      ml: true,
      mr: true,
      bl: true,
      br: true,
      tl: true,
      tr: true,
      mtr: false,
    });
  }

  controlsAboveOverlay = true;

  fill = 'rgba(0, 0, 0, 0)';

  render(ctx: CanvasRenderingContext2D) {
    const canvas = this.canvas as FabricCanvas;
    var ctx = canvas.contextTop; // 使用 contextTop，不会影响底层对象
    ctx.clearRect(0, 0, canvas.width!, canvas.height!); // 清除原有内容

    // 绘制半透明灰色背景
    ctx.save();
    ctx.globalCompositeOperation = 'source-over'; // 普通的叠加模式
    ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
    ctx.fillRect(0, 0, canvas.width!, canvas.height!);
    // 使用裁剪模式擦除矩形区域的灰色
    ctx.clearRect(this.left!, this.top!, this.getScaledWidth(), this.getScaledHeight());
    ctx.restore();

    const lowerCtx = canvas.getContext();
    lowerCtx.drawImage(ctx.canvas, 0, 0, canvas.width!, canvas.height!);
  }
}
